# -*- coding: utf-8 -*-

# Copyright 2003-2007 Jarek Zgoda <jarek.zgoda@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

"""Main program window"""

__revision__ = '$Id: frmmain.py 10 2008-02-04 21:21:22Z jarek.zgoda $'

import os
import Queue
import webbrowser
import time
import urllib

import gobject
import gtk
import gtk.glade

import const, threads, forms

class MainWindow(object):

    def __init__(self):
        self.widgets = gtk.glade.XML(const.GLADE_PATH, 'form_main', 'leechfm')
        self.widgets.signal_autoconnect(self)
        self.window = self.widgets.get_widget('form_main')
        self.window.set_icon_from_file(const.APP_ICON)
        self.popup_menuitems = gtk.glade.XML(const.GLADE_PATH, 'pm_main',
            'leechfm')
        self.popup_menuitems.signal_autoconnect(self)
        self.popup_menu = self.popup_menuitems.get_widget('pm_main')
        self.idle_timer = None
        self.queue = Queue.Queue()
        self._init_widgets()

    def show(self):
        self.window.present()

    def _init_widgets(self):
        users_completion = gtk.EntryCompletion()
        users_history = gtk.ListStore(str)
        self._load_completion_history(users_history, 'users')
        users_completion.set_model(users_history)
        entry = self.widgets.get_widget('entry_username')
        entry.set_completion(users_completion)
        users_completion.set_text_column(0)
        tv_results = self.widgets.get_widget('tv_results')
        model = gtk.ListStore(str, str, str)
        tv_results.append_column(gtk.TreeViewColumn(_('Artist'),
            gtk.CellRendererText(), text=2))
        tv_results.append_column(gtk.TreeViewColumn(_('Torrent title'),
            gtk.CellRendererText(), text=0))
        tv_results.set_model(model)

    def _load_completion_history(self, store, history):
        file_name = os.path.join(const.USER_DIR, '%s.history' % history)
        if os.path.isfile(file_name):
            fp = open(file_name)
            try:
                lines = fp.read().strip().split('\n')
                lines.sort()
                for line in lines:
                    store.append((line.strip(), ))
            finally:
                fp.close()

    def _save_completion_history(self, store, history):
        lines = []
        for row in store:
            lines.append(row[0])
        file_name = os.path.join(const.USER_DIR, '%s.history' % history)
        if not os.path.isdir(const.USER_DIR):
            os.makedirs(const.USER_DIR)
        fp = open(file_name, 'w')
        try:
            fp.write('\n'.join(lines))
        finally:
            fp.close()

    def _pulse(self):
        progress_update = self.widgets.get_widget('progress_update')
        try:
            time.sleep(0.1)
            progress_update.pulse()
            title, url, artist = self.queue.get_nowait()
            if title == 'finish' and url is None:
                progress_update = self.widgets.get_widget('progress_update')
                progress_update.hide()
                label = self.widgets.get_widget('label_results')
                return False
            self._add_entry(title, url, artist)
        except Queue.Empty:
            pass
        return True

    def _add_entry(self, title, url, artist):
        tv_results = self.widgets.get_widget('tv_results')
        model = tv_results.get_model()
        model.append((title, url, artist))

    def delete_event(self, widget, event, data=None):
        if self.idle_timer:
            gobject.source_remove(self.idle_timer)
        entry = self.widgets.get_widget('entry_username')
        store = entry.get_completion().get_model()
        self._save_completion_history(store, 'users')
        gtk.main_quit()

    def on_entry_activate(self, entry):
        text = entry.get_text().strip()
        if text:
            store = entry.get_completion().get_model()
            if text not in [row[0] for row in store]:
                store.append((text, ))
            thread = threads.RecommendationsFetcher(text, self.queue)
            self.idle_timer = gobject.idle_add(self._pulse)
            tv_results = self.widgets.get_widget('tv_results')
            model = tv_results.get_model()
            model.clear()
            thread.setDaemon(True)
            progress_update = self.widgets.get_widget('progress_update')
            progress_update.show()
            thread.start()

    def on_tv_results_button_press_event(self, *args):
        widget, event = args
        url, artist = self._get_data_from_list()
        if not (None in (url, artist)):
            if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
                # double click on list item
                webbrowser.open_new_tab(url)
            elif event.button == 3:
                # right click on list view
                self.popup_menu.popup(None, None, None, event.button, event.time)

    def on_btn_about_clicked(self, *args):
        forms.show_about_dialog()

    def on_mi_open_torrent_page_activate(self, *args):
        url, artist = self._get_data_from_list()
        webbrowser.open_new_tab(url)

    def on_mi_open_lastfm_artist_page_activate(self, *args):
        url, artist = self._get_data_from_list()
        artist_url = 'http://www.last.fm/music/%s' % urllib.quote_plus(artist)
        webbrowser.open_new_tab(artist_url)

    def _get_data_from_list(self):
        tv_results = self.widgets.get_widget('tv_results')
        model, iterator = tv_results.get_selection().get_selected()
        url, artist = None, None
        if iterator:
            url = model.get_value(iterator, 1)
            artist = model.get_value(iterator, 2)
        return url, artist
